﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Canyala.Lagoon.Extensions;

namespace Canyala.Lagoon.Collections 
{
    public class Bag<T> : IEnumerable<KeyValuePair<T, int>>
    {
        private Dictionary<T, int> _bag = new Dictionary<T,int>();

        public Bag ()
	        {}

        public Bag(IEnumerable<T> seq)
            { seq.Do(Add); }

        public void Add(T element)
        {
            if (!_bag.ContainsKey(element)) 
                _bag.Add(element, 1);
            else 
                _bag[element]++;
        }

        public int this[T element]
            { get { return Count(element); } }

        public int Count(T element)
        {
            int count = 0;
            _bag.TryGetValue(element, out count);
            return count;
        }

        public bool Contains(T element)
            {  return Count(element) > 0; }

        public IEnumerator<KeyValuePair<T, int>> GetEnumerator()
            { return _bag.GetEnumerator(); }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            { return _bag.GetEnumerator(); }
    }
}
